package Controller;

import java.util.concurrent.TimeUnit;

/**
 * @author: tangBin
 * @Date: 2022/1/5 0005 16:00
 * @Description: 使用 volatile 开关控制  线程关闭
 */
public class VolatileExample {

    static class MyTask extends Thread {
        private volatile boolean closed = false;

        @Override
        public void run() {
            System.out.println("我开始工作了");
            do {
                System.out.println("正常上班中");
            } while (!closed && !isInterrupted());

            System.out.println("开始下班了");
        }

        public void close() {
            this.closed = true;
            this.interrupt();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyTask myTask = new MyTask();
        myTask.start();
        TimeUnit.SECONDS.sleep(10);
        System.out.println("上班已经结束了");
        myTask.close();
    }

}
